package cn.chenyumeng.blog.controller.blog;

import cn.chenyumeng.blog.dto.BlogDTO;
import cn.chenyumeng.blog.dto.CommentDTO;
import cn.chenyumeng.blog.dto.CommonResponse;
import cn.chenyumeng.blog.dto.ResultCode;
import cn.chenyumeng.blog.service.EmailService;
import cn.chenyumeng.blog.service.blog.BlogPageServer;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @program: blog->BlogContentPageController
 * @description:
 * @author: cg
 * @create: 2020-08-10 18:34
 **/
@Validated
@RestController
@ResponseBody
@RequestMapping("/blog/blogContent")
public class BlogPageController {

    @Autowired
    private BlogPageServer blogPageServer;

    @Autowired
    private EmailService emailService;

    @GetMapping("/getBlogById")
    public CommonResponse getBlogById(@NotNull(message = "博客Id不能为空") Long id) {
        System.err.println(id);
        BlogDTO blogDTO = blogPageServer.getAndConvert(id);
        if (blogDTO == null) {
            return CommonResponse.build(ResultCode.PARAM_IS_INVALID);
        }
        return CommonResponse.ok(blogDTO);
    }

    @GetMapping("/getCommentListByBlogIdAndLimit")
    public CommonResponse getCommentListByBlogIdAndLimit(@NotNull(message = "博客Id不能为空") Long id,
                                                         @RequestParam(name = "page", defaultValue = "1") Integer page,
                                                         @RequestParam(name = "size", defaultValue = "8") Integer size) {
        PageInfo<List<CommentDTO>> pageInfo = blogPageServer.getCommentListByBlogId(id, page, size);
        if (pageInfo == null) {
            return CommonResponse.build(ResultCode.PARAM_IS_INVALID);
        }
        return CommonResponse.ok(pageInfo);
    }

    @PostMapping("/addCommentByComment")
    public CommonResponse addCommentByComment(CommentDTO comment) {
        if (blogPageServer.addCommentByComment(comment) > 0) {
            // 子评论并需要通知
            if (comment.getParentCommentId() != null) {
                CommentDTO dto = blogPageServer.getCommentByCommentId(comment.getParentCommentId());
                if (dto.getNotice()!=null) {
                    emailService.sendSimple(dto.getEmail(), dto.getNotice());
                }
            }
            return CommonResponse.ok();
        } else {
            return CommonResponse.build(ResultCode.PARAM_IS_INVALID);
        }
    }

}
